<template>
        <div class="use">
              <span @click="isMsgLogin = true" v-if="isMsgLogin === false"><i class="iconfont icon-msg" ></i>使用短信登录</span>
              <span @click="isMsgLogin = false" v-if="isMsgLogin === true"><i class="iconfont icon-user" ></i>使用账号登录</span>
          </div>
          <!-- 输入框 -->
          <Form ref="formCom" :validation-schema="schema" autocomplete="off" v-slot="{errors}">
          <template v-if="isMsgLogin === false">
              <div class="top" >
              <Field  name="account" v-model="form.account" type="text" :class="{active:errors.account}"  class="user" placeholder="请输入用户名" />
                <i class="iconfont icon-user"></i>
                <div v-if="errors.account" class="error"><i class="iconfont icon-warning"></i> {{errors.account}}</div>
          </div>
          <div class="top pas" >
              <Field name="password" v-model="form.password" :class="{active:errors.password}" type="password" class="user" placeholder="请输入密码" />
                <i class="iconfont icon-lock"></i>
                <div v-if="errors.password" class="error"><i class="iconfont icon-warning"></i> {{errors.password}}</div>
          </div>
          </template>
          <template v-if="isMsgLogin === true">
              <div class="top">
              <Field  name="mobile" :class="{active:errors.mobile}" v-model="form.mobile" type="text" class="user" placeholder="请输入手机号" />
                <i class="iconfont icon-user"></i>
                <div class="error" v-if="errors.mobile"><i class="iconfont icon-warning"></i> {{errors.mobile}}</div>
          </div>
          <div class="top pas" >
              <Field name="code" :class="{active:errors.code}"  v-model="form.code" type="number" class="user" placeholder="请输入验证码" />
                <i class="iconfont icon-code"></i>
                <span @click="send()">
                  {{time <= 0 ?  '发送验证码':`${time}秒后发送`}}
                </span>
                <div class="error" v-if="errors.code"><i class="iconfont icon-warning"></i> {{errors.code}}</div>
          </div>
          </template>
            <!-- /输入框 -->
            <div class="tiaokuan"> <Field as="XtxCheckbox" @click="form.isAgree = !form.isAgree" name="isAgree" v-model="form.isAgree"/> 我已同意<span>《隐私条款》</span>和<span>《服务条款》</span>
            <div class="error" v-if="errors.isAgree" ><i class="iconfont icon-warning"></i> {{errors.isAgree}}</div>
            </div>
            <div class="button"><a @click="login" class="btn-button">登录</a></div>
          </Form>
            <div class="zhuce">
              <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
              <img  src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
              </a>

                <div class="zhece">
                    <span class="one">忘记密码</span>
                    <span>免费注册</span>
                </div>
            </div>
</template>

<script>

import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import Message from '@/components/libaray/Message'
import { onUnmounted, reactive, ref, watch } from 'vue'
import { findUser, userAccountLoginMsg, userMobileLogin } from '@/api/user'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { useIntervalFn } from '@vueuse/core'
// import QC from 'qc'
export default {
  name: 'LoginForm',
  components: {
    Form,
    Field
  },
  setup () {
    //  切换短信登陆
    const isMsgLogin = ref(false)
    console.log(isMsgLogin)
    // 表单数据对象
    const form = reactive({
      isAgree: true,
      account: null,
      password: null,
      mobile: null,
      code: null
    })
    // vee-validate校验基本步骤
    // 1.导入Form,File组件  将form和input进行替换,需要加上name,name用来指定校验规则函数
    // 2.Field需要进行数据绑定,字段名称最好和后台接口需要的一致
    // 3.编写name属性对应的校验规则函数  form的validation-schema接收定义好的校验规则,是个对象
    const myschema = {
      // 校验函数有规则:返回true就是校验成功,返回一个字符串就是失败,错误提示
      account: schema.account,
      password: schema.password,
      mobile: schema.mobile,
      code: schema.code,
      isAgree: schema.isAgree
    }
    // 监听isMsgLogin重置表单数据
    watch(isMsgLogin, () => {
      console.log('切换了')
      form.isAgree = true
      form.account = null
      form.password = null
      form.mobile = null
      form.code = null
    })
    // setup中获取组件实例
    // const { proxy } = getCurrentInstance()
    // proxy.$message({ message: '123' })
    // 对整体表单校验
    const formCom = ref(null)
    const router = useRouter()
    const store = useStore()
    const route = useRoute()
    const login = async () => {
    // Form组件提供了一个validate函数作为整体校验,返回的是promise
      // 准备一个API组账号登陆
      // 调用API函数
      // 3.成功：跳转登录页或者首页
      await formCom.value.validate()
      let data = null
      try {
        if (isMsgLogin.value) {
        // 手机号登陆
        // 1.发送验证码
        // 1.1绑定发送验证码按钮点击事件
        // 1.2校验手机号,如果成功才去发送短信
        // 13.校验失败，失败的校验样式显示出来

          // 2.手机号登录

          data = await userMobileLogin({
            mobile: form.mobile,
            code: form.code
          })
        } else {
        // 账号密码登录
          data = await findUser(form)
        }
        store.commit('user/setUser', {
          id: data.result.id,
          avatar: data.result.avatar,
          nickname: data.result.nickname,
          account: form.account,
          mobile: data.result.mobile,
          token: data.result.token
        })
        store.dispatch('cart/mergeCart').then(() => {
          // 进行跳转
          router.push(route.query.redirectUrl || '/')
          // 成功提示消息
          Message({ type: 'success', message: '登录成功' })
        })
      } catch (err) {
        if (err.response.data) {
          Message({ type: 'error', message: err.response.data.message || '登录失败' })
        }
      }
    }
    // pause暂停，resume开始
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    // 发送短信
    onUnmounted(() => {
      pause()
    })
    const send = async () => {
      const valid = myschema.mobile(form.mobile)
      if (valid === true) {
        // 通过
        // 没有倒计时才可以发送请求
        if (time.value === 0) {
          try {
            await userAccountLoginMsg(form.mobile)
            Message({ type: 'success', message: '发送成功' })
            time.value = 60
            resume()
          } catch (err) {
            Message({ type: 'error', message: '用户不存在' })
          }
        }
      } else {
        // 失败,使用vee的错误函数显示错误信息 setFieldError(字段名称,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    // 初始化QQ登录
    // onMounted(() => {
    //   // 1.准备span有id
    //   // 2.QC.login({btnId:'qqLoginBtn'})
    //   QC.Login({ btnId: 'qqLoginBtn' })
    // })
    return { isMsgLogin, form, schema: myschema, login, formCom, send, time }
  }
}
</script>

<style scoped lang="less">
.use {
            display: flex;
            justify-content: flex-end;
            margin: 15px 0;
            font-size: 14px;
            color: @xtxColor;
            span {
                cursor: pointer;
                vertical-align: middle;
                i {
                vertical-align: middle;
            font-size: 14px;
                margin-right: 5px;
            }
            }

        }
        .top {
            width: 100%;
            height: 38px;
        // border: 1px solid #ccc;
            position: relative;
            .user {
            width: 100%;
            padding: 0;
            outline: none;
            border: 1px solid #ccc;
            height: 100%;
            padding-left: 50px;
            line-height: 38px;
             &.active {
            border-color: red;
        }
            &.ac,&:focus {
            border-color: @xtxColor ;
          }
        }
        .error {
            color: red;
            font-size: 12px;
            padding-top: 5px;
        }
        span {
            height: 36px;
            position: absolute;
            top: 1px;
            right: 1px;
            width: 90px;
            background-color: #f5f5f5;
            text-align: center;
            line-height: 36px;
            color: #666;
            font-size: 14px;
            cursor: pointer;
        }
        > i {
            position: absolute;
            height: 36px;
            width: 40px;
            background-color: #cfcdcd;
            font-size: 20px;
            line-height: 36px;
            text-align: center;
            color: #fff;
            top: 1px;
            left: 1px;
        }
        }
         .pas  {
           margin-top: 30px;
       }
       .tiaokuan {
           margin: 30px 0;
           font-size: 14px;
           vertical-align: middle;
           span {
               color: #069;
               cursor: pointer;
           }
           .error {
          color: red;
            font-size: 12px;
            padding-top: 5px;
        }
       }
       .button {
           .btn-button {
             display: inline-block;
               width: 100%;
               height: 40px;
               background-color: @xtxColor;
               line-height: 40px;
               text-align: center;
               border: @xtxColor;
               color: #fff;
               cursor: pointer;
           }
       }
       .zhuce {
           display: flex;
           justify-content: space-between;
           align-items: center;
           margin-top: 20px;
           img {
               cursor: pointer;
           }
        span {
            cursor: pointer;
            color: #999;
        }
        .one {
            margin-right: 8px;
        }
       }
</style>
